<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserModel
 *
 * @author Marko
 */
class Fina_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    function fina_base_time_for_event($year, $pool, $gender, $relay, $distance, $stroke) {
        if ($distance <= 25)
            return 0;
        if ($relay == 1)
            $distance /= 4;
//    echo $result_ms . ' - ' . $year . ' - ' . $pool . ' - ' . $gender . ' - ' . $relay . ' - ' . $distance . ' - ' . $stroke;
        $result = mysql_query("SELECT `time_ms` FROM `fina` WHERE `year`<=$year and `pool`=$pool AND UPPER(gender)=UPPER('$gender') AND 
        `relay`=$relay and `distance`=$distance and UPPER(stroke)=UPPER('$stroke') ORDER BY `year` DESC LIMIT 1") or die(mysql_error());
        if (mysql_num_rows($result) == 0) {
            return 0;
        }
        return mysql_result($result, 0);
    }
    
    public function fetch_fina_admin_table() {
        $this->db->select('year, pool, count(id) as no', false)->from('fina')->group_by('year, pool')->order_by('year');
        return $this->db->get()->result();
    }

    function fina_points_for_result($basetime, $result_ms) {
        if ($result_ms == 0 || $basetime == 0)
            return 0;
        return (int) (1000 * pow($basetime / $result_ms, 3));
    }

    function exists_fina_record($year, $pool, $gender, $relay, $distance, $stroke, $time_ms) {
        $result = mysql_query("SELECT count(`id`) FROM `fina` WHERE `year`=$year and `pool`=$pool and UPPER(`gender`)=UPPER('$gender') and 
        `relay`=$relay and `distance`=$distance and UPPER(`stroke`)=UPPER('$stroke') and `time_ms`=$time_ms") or die(mysql_error());
        return mysql_result($result, 0) >= 1;
    }

    function insert_fina_table_to_db(array $fina) {
        $query = "INSERT INTO `fina`(`year`, `pool`, `gender`, `relay`, `distance`, `stroke`, `time_ms`) VALUES ";
        $fields = '';
        foreach ($fina as $row) {
            $row = strtolower($row);
            $line = explode(';', $row);
            if (!is_numeric($line[0])) {
                continue;
            }
            $line[1] = ($line[1] == 'scm' ? 25 : 50);
            $line[3] = ($line[3] == 1 ? 0 : 1);
            $line[6] = str_replace(',', '.', $line[7]) * 1000;
            unset($line[7]);

            if (!$this->exists_fina_record($line[0], $line[1], $line[2], $line[3], $line[4], $line[5], $line[6]))
                $fields .= '(\'' . implode('\', \'', $line) . '\'), ';
        }
        if ($fields != '') {
            $fields = substr($fields, 0, strlen($fields) - 2);

            $query .= $fields;
//            echo $query;
            mysql_query($query) or die(mysql_error());
        }
    }

}

?>
